package org.bpms.controller.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.Cookie;

import org.bpms.interceptor.WebInterceptor;
import org.bpms.model.admin.Smenu;
import org.bpms.model.admin.Suser;
import org.bpms.plugins.bjui.BjuiRender;
import org.bpms.service.admin.LogService;
import org.bpms.service.admin.MenuService;
import org.bpms.service.admin.UserService;
import org.bpms.util.CaptchaRender;
import org.bpms.util.Encrypt;

import com.jfinal.aop.Clear;
import com.jfinal.aop.Enhancer;
import com.jfinal.core.Controller;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.redis.Redis;
/**
 * 后台用户登录等控制器
 * @author hupei
 *
 */
@Clear(WebInterceptor.class)
public class AdminController extends Controller {
	private MenuService menuService = Enhancer.enhance(MenuService.class);
	private UserService service = Enhancer.enhance(UserService.class);
	private LogService  logService = Enhancer.enhance(LogService.class);
	/**
	 * 打开登陆页面
	 */
	@Clear
	public void index(){
		render("/admin/login.html");
	}
	
	/**
	 * 登陆成功后跳转
	 */
	public void info(){
		String type = getPara("type","wide");//wide是宽版,默认narrow是窄版
		String sessionId = getCookie("adminsession");
		Suser user = Redis.use().get(sessionId);
		List<Smenu> smenus = new ArrayList<Smenu>();
		Smenu menu = new Smenu();
		//为获取顶层菜单设置id、pid
		menu.set("id", null);
		menu.set("pid", null);
		menuService.allChildMenu(smenus, user.getStr("id"), menu);
		creatMenu(smenus);
		setAttr("user", user);
		setAttr("pmenus", smenus);//所有菜单
		render("/admin/index_tree.html");
	}
	
	/**
	 * 主页
	 */
	public void myhome(){
		render("/admin/home.html");
	}
	
	/**
	 * 超时后跳转弹出登陆窗口
	 */
	@Clear
	public void tologin(){
		String username = getPara("username", "");
		setAttr("username", username);
		render("/admin/login_page.html");
	}
	
	/**
	 * 注销
	 */
	@Clear
	public void loginout(){
		String sessionId = getCookie("adminsession");
		Suser user = Redis.use().get(sessionId);
		logService.create(user.getStr("username"), "注销登陆");
		removeSessionAttr("user");
		render("/admin/login.html");
	}
	/**
	 * 登陆
	 */
	@Clear
	public void login(){
		Map<String, Object> map = new HashMap<String , Object>();
		String username = getPara("username");
		String password = Encrypt.e(getPara("password"));
		String inputRandomCode = getPara("captcha");
		
		if (!CaptchaRender.validate(this, inputRandomCode))
		{
			map.put("success", false);
			map.put("state", 1);
			map.put("msg", "验证码错误");
		}else{
			//业务层必须用Enhancer增强才能开启事务
			Suser user = service.login(username, password);
			
			if (null == user)
			{
				map.put("success", false);
				map.put("state", 2);
				map.put("msg", "用户名密码错误");			
			}
			else
			{
				if (user.getInt("isactive") == 1){
					//setSessionAttr("user", user);//保存到session中
					String sessionId = UUID.randomUUID().toString();
					Cookie cookie = new Cookie("adminsession", sessionId);
					cookie.setMaxAge(-1);
					cookie.setPath("/");
					cookie.setMaxAge(7 * 24 * 3600);
					setCookie(cookie);
					CacheKit.put("adminsession", "session" , sessionId);
					Redis.use().setex(sessionId, 7 * 24 * 3600 , user);
					logService.create(user.getStr("username"), "登陆系统");
					map.put("success", true);
					map.put("state", 0);
					map.put("msg", "登陆成功");	
				}else{
					map.put("success", false);
					map.put("state", 2);
					map.put("msg", "账户被禁用");						
				}		
			}			
		}
		renderJson(map);
	}
	/**
	 * 超时时弹窗登陆
	 */
	@Clear
	public void logincheck(){
		String username = getPara("username");
		String password = Encrypt.e(getPara("password"));
		String inputRandomCode = getPara("captcha");
		
		if (!CaptchaRender.validate(this, inputRandomCode))
		{
			render(BjuiRender.error("验证码错误！"));
		}else{
			//业务层必须用Enhancer增强才能开启事务
			Suser user = service.login(username, password);
			
			if (null == user)
			{
				render(BjuiRender.error("账号或密码错误！"));		
			}
			else
			{
				if (user.getInt("isactive") == 1){
					String sessionId = UUID.randomUUID().toString();
					Cookie cookie = new Cookie("adminsession", sessionId);
					cookie.setMaxAge(-1);
					cookie.setPath("/");
					cookie.setMaxAge(7 * 24 * 3600);
					setCookie(cookie);
//					CacheKit.put("adminsession", "session" , sessionId);
					Redis.use().setex(sessionId, 7 * 24 * 3600 , user);
					//setSessionAttr("user", user);//保存到session中
					render(BjuiRender.success("登录成功！"));
				}else{
					render(BjuiRender.error("账户被禁用！"));						
				}	
			}			
		}
	}
	
	/**
	 * 针对顶层菜单变换
	 * @param smenus
	 */
	public void creatMenu(List<Smenu> smenus){
		for (Smenu menu : smenus){//顶层
			List<Smenu> csmenus = menu.getSmenus();
			if (null != csmenus && csmenus.size() > 0){
				for (Smenu temp : csmenus){//第二层
					if (null == temp.getSmenus() || temp.getSmenus().size() == 0){
						menu.setHaveChild(1);
						break;
					}
				}
			}
			if (menu.getHaveChild() == 1){
				List<Smenu> newsmenus = new ArrayList<Smenu>();
				for (Smenu temp : menu.getSmenus()){
					if (null == temp.getSmenus() || temp.getSmenus().size() == 0){
						newsmenus.add(temp);
					}
				}
				menu.getSmenus().removeAll(newsmenus);
				newsmenus.addAll(menu.getSmenus());
				menu.setSmenus(newsmenus);
			}
		}
	}
	
	/**
	 * 图片验证码
	 */
	@Clear
	public void captcha(){
		render(new CaptchaRender(150,35,5,true));
	}
}
